package com.junoppa.seckill.controller;

import com.google.common.util.concurrent.RateLimiter;
import com.junoppa.seckill.entity.Order;
import com.junoppa.seckill.service.OrderService;
import com.junoppa.seckill.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author junoppa
 */
@RestController
@RequestMapping("ms")
public class SeckillController {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private OrderService orderService;


    // 创建令牌桶实例//每秒产生多少个token
    private RateLimiter rateLimiter = RateLimiter.create(50);

    @GetMapping("/kill")
    public String kill(@RequestParam(value = "uid" ,required = true) String uid) {
        boolean flag =false;
        try {
            //检查访问频率
            flag = seckillService.allowVisit(uid);
        } catch (Exception e) {
            return e.getMessage();
        }
        if(flag){
            // 调用服务层业务之前进行限流
            if (!rateLimiter.tryAcquire(2, TimeUnit.SECONDS)) {
                return "抢购过于火爆，请重试~~~";
            }
            try {
                int id = 1;
                int i = seckillService.kill(id);
               if(i==1){
                   Order order = new Order();
                   order.setUid(uid);
                   orderService.insertOrder(order);
                   return uid+"您秒杀成功了！";
               }else {
                   return "秒杀已经结束！";
               }

            } catch (Exception e) {
                return e.getMessage();
            }
        }else{
            return  uid+"您已经秒杀过了";
        }

    }

}
